package com.huicheng.utils;

import android.text.TextUtils;
import android.util.Log;

import com.huicheng.App;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

import static android.content.ContentValues.TAG;

/**
 * Created by adolph on 18-1-13.
 */

public class HttpUtil {

    /**
     * http put 请求
     * @param url       请求url
     * @return          Response请求结果实例，通过response.code==200判断
     */
    public static String httpPost(String url,String data) {
        Log.d("lk","[HttpUtil] [httpPost]");
        MediaType JSON = MediaType.parse("application/json");

        OkHttpClient client = App.okHttpClient;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("appmsg",data);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        FormBody.Builder builder = new FormBody.Builder();
        builder.add("appmsg",data);


        RequestBody body = RequestBody.create(JSON, jsonObject.toString());
//        RequestBody body = RequestBody.create(JSON, builder.toString());
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Content-Type", "application/json")
                .put(body)
                .build();

       return proceedRequest(client, request);

    }

    private static String proceedRequest(OkHttpClient client, Request request) {
        Log.d("lk","[HttpUtil] [proceedRequest]");
        try {
//            client.newCall(request).execute();
            okhttp3.Response temp = client.newCall(request).execute();
            Log.d("lk","[HttpUtil] [proceedRequest]Response:" +temp.toString());
            ResponseBody body = temp.body();
            String response = body.string();
            Log.d("lk","[HttpUtil] [proceedRequest]Response:" +response);
            if (TextUtils.equals(response,"200")) {
                Log.d("lk","[HttpUtil] [proceedRequest] 上报成功");
            }else {
                Log.d("lk","[HttpUtil] [proceedRequest] 上报失败");
            }
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            Log.w(TAG, e.getMessage() == null ? " " : e.getMessage());
        }
        return null;
    }
}
